package com.sgb.zhaocai.view.demand.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.zhaocai.R;
import com.sgb.zhaocai.databinding.ActivityNewAddProjectBinding;
import com.sgb.zhaocai.entity.MapLongAndLatEntity;
import com.sgb.zhaocai.entity.ProjectIssueBean;
import com.sgb.zhaocai.entity.PublishListBean;
import com.sgb.zhaocai.viewmodel.NewAddProjectModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.view.areapopup.AddressEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * Time:2021/9/18
 * AUTHOR:F_Q
 * Description:需求预告-需求发布-新增项目
 */
public class NewAddProjectActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityNewAddProjectBinding mBinding;
    private NewAddProjectModel mModel;
    //工程类型
    private List<PublishListBean> ProjectTypeList;
    // 地址一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 地址二级联动数据
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 地址三级联动数据
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private String lat;
    private String lng;
    private List<String>   addresscode = new ArrayList<>();
    ProjectIssueBean bean = new ProjectIssueBean();

    public static void start(Activity context, int requestCode) {
        Intent intent = new Intent(context, NewAddProjectActivity.class);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_new_add_project);
        mModel = new ViewModelProvider(this).get(NewAddProjectModel.class);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> onBackPressed());
        mBinding.includeTitle.titleView.setText("新增项目");
        mBinding.projectType.setOnWholeItemClickListener(this);//工程类型
        mBinding.projectAddress.setOnWholeItemClickListener(this);//项目地址
        mBinding.detailedAddress.setOnWholeItemClickListener(this);//详细地址
        mBinding.cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mBinding.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataBase();
            }
        });
    }


    @Override
    public void OnWholeItemClick(View view) {
        //工程类型
        if (view.getId() == R.id.project_type) {
            if (ProjectTypeList == null) {
                mModel.getProjectTypeList(this, view);
            } else {
                showListPop("工程类型", ProjectTypeList);
            }
        }
        //项目地址
        if (view.getId() == R.id.project_address) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                mModel.getAddressModel(this);
            }
        }
        //详细地址
        if (view.getId() == R.id.detailed_address) {
            if(!TextUtils.isEmpty(mBinding.projectAddress.getContent())){
                Intent intent = new Intent();
                intent.setClass(this, ZhaoCaiMapAddressActivity.class);
                intent.putExtra(ZhaoCaiMapAddressActivity.TITLE, "详细地址");
                intent.putExtra(ZhaoCaiMapAddressActivity.HINT, "请输入地址");
                intent.putExtra(ZhaoCaiMapAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(ZhaoCaiMapAddressActivity.LATITUDE, Double.parseDouble(lat));
                intent.putExtra(ZhaoCaiMapAddressActivity.LONGTITUDE, Double.parseDouble(lng));
                startActivityForResult(intent, 255);
            }else {
                MToast.showToast(this, "请选择项目地址");
            }
        }
    }

    /**
     * 一级选择弹窗
     *
     * @param titles
     * @param data
     */
    private void showListPop(String titles, List<PublishListBean> data) {
        if (data != null && data.size() > 0) {
            OptionsPickerView<PublishListBean> mCustomerOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mBinding.projectType.setContent(data.get(options1).getName());
                    bean.setEngineeringType(data.get(options1).getName());
                }
            }).setCancelColor(Color.parseColor("#666666"))
                    .setSubCalSize(15)
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitColor(Color.parseColor("#5792FD")).build();
            mCustomerOptions.setTitleText(titles);
            mCustomerOptions.setPicker(data);
            mCustomerOptions.setSelectOptions(0);
            mCustomerOptions.show();
        }
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
           //     bean.setAreaNo("");
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
         //       bean.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String provinceName = addressEntityList.get(options1).getName();
            String cityName = opt2.get(options1).get(options2).getName();
            if (!TextUtils.isEmpty(cityName)) {
                if (!TextUtils.isEmpty(areaName)) {
                    mBinding.projectAddress.setContent(provinceName + "/" + cityName + "/" + areaName);
                } else {
                    mBinding.projectAddress.setContent(provinceName + "/" + cityName);
                }
            } else {
                mBinding.projectAddress.setContent(provinceName);
            }
            bean.setProjectAddressName(mBinding.projectAddress.getContent());
            addresscode.add(addressEntityList.get(options1).getId());
            if (!TextUtils.isEmpty(opt2.get(options1).get(options2).getNo())){
                addresscode.add(opt2.get(options1).get(options2).getNo());
            }
            if (opt3.get(options1).get(options2).get(options3)!=null&&!TextUtils.isEmpty(opt3.get(options1).get(options2).get(options3).getNo())){
                addresscode.add(opt3.get(options1).get(options2).get(options3).getNo());
                mModel.getLocationLL(this, addressEntityList.get(options1).getId(), opt2.get(options1).get(options2).getNo(), opt3.get(options1).get(options2).get(options3).getNo());
            }else {
                mModel.getLocationLL(this, addressEntityList.get(options1).getId(), opt2.get(options1).get(options2).getNo(), "");
            }
            bean.setProjectAddress(addresscode);
            mBinding.detailedAddress.setContent("");
            bean.setAddrDetailLat("");
            bean.setAddrDetailLng("");
            bean.setAddrDetail("");
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD")).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    /**
     * 保存数据
     */
    private void DataBase() {
        if (TextUtils.isEmpty(mBinding.projectName.getContent())) {
            MToast.showToast(this, "请输入项目名称");
            return;
        } else {
            bean.setProjectName(mBinding.projectName.getContent());
        }
        if (TextUtils.isEmpty(mBinding.projectAddress.getContent())) {
            MToast.showToast(this, "请选择项目地址");
            return;
        }
        if (TextUtils.isEmpty(mBinding.detailedAddress.getContent())) {
            MToast.showToast(this, "请选择详细地址");
            return;
        }
        if (TextUtils.isEmpty(mBinding.projectType.getContent())) {
            MToast.showToast(this, "请选择工程类型");
            return;
        }
        bean.setAuditStatus("5");
        bean.setAnnounce("0");
        mModel.saveOrUpdateProject(this, bean);
    }


    /**
     * 返回经纬度信息
     *
     * @param data
     */
    public void updateAddress(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                if (!TextUtils.isEmpty(data.getLat())) {
                    lat = data.getLat();
                } else {
                    lat = "0";
                }
                if (!TextUtils.isEmpty(data.getLng())) {
                    lng = data.getLng();
                } else {
                    lng = "0";
                }
            }
        }
    }

    /**
     * 工程类型
     *
     * @param data
     * @param view
     */
    public void setProjectTypeList(List<PublishListBean> data, View view) {
        if (TextUtils.equals(data.get(0).getName(), "不限")) {
            data.remove(0);
        }
        this.ProjectTypeList = data;
        showListPop("工程类型", data);
    }

    /**
     * 地址信息
     *
     * @param data
     */
    public void setAddressList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        initJsonData();
        showCityPop();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255) {
                if (data == null) {
                    return;
                }
                double lat = data.getDoubleExtra(ZhaoCaiMapAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(ZhaoCaiMapAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(ZhaoCaiMapAddressActivity.CURRENT_POSITION);
                mBinding.detailedAddress.setContent(address + "");
                bean.setAddrDetailLat(lat + "");
                bean.setAddrDetailLng(lon + "");
                bean.setAddrDetail(address);
            }
        }
    }

    @Override
    public void onBackPressed() {
        initDialog();
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("温馨提示")
                .setMsg("此操作将丢失当前表单填写内容,\n是否继续?")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        setResult(RESULT_OK, new Intent());
                        NewAddProjectActivity.this.finish();
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }

    public void setSaveOrUpdateProject(String auditStatus) {
        MToast.showToast(this, "保存成功");
        setResult(RESULT_OK, new Intent());
        finish();
    }
}
